package com.ruoyi.project.orderSystem.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.enums.OrderStatus;
import com.ruoyi.common.enums.OrderType;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.seqGen.SeqGenTool;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.configureSystem.domain.VStation;
import com.ruoyi.project.configureSystem.mapper.VStationMapper;
import com.ruoyi.project.orderSystem.domain.*;
import com.ruoyi.project.orderSystem.domain.vo.WorkOrderVO;
import com.ruoyi.project.orderSystem.mapper.*;
import com.ruoyi.project.query.WorkOrderQuery;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.orderSystem.service.IWorkOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工单Service业务层处理
 *
 * @author wangshuo
 * @date 2021-01-24
 */
@Service
public class WorkOrderServiceImpl implements IWorkOrderService
{
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private OrderStationMapper orderStationMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private OrderStationItemMapper orderStationItemMapper;
    @Autowired
    private StationItemFileMapper stationItemFileMapper;
    @Autowired
    private WorkOrderAuditMapper workOrderAuditMapper;
    @Autowired
    private VStationMapper vStationMapper;

    /**
     * 查询工单
     *
     * @param id 工单ID
     * @return 工单
     */
    @Override
    public WorkOrder selectWorkOrderById(Long id)
    {
        WorkOrder workOrder = workOrderMapper.selectWorkOrderById(id);
        String[] split = workOrder.getExecutorIds().split(",");
        long[] longs = Arrays.stream(split).mapToLong(Long::valueOf).toArray();
        workOrder.setExecutorIdArr(longs);
        if(workOrder.getOrderStatus()==OrderStatus.ORDER_COMPLETED.getKey().intValue()){
            //获取巡检站点以及巡检项
            OrderStation orderStation = new OrderStation();
            orderStation.setOrderId(id);
            List<OrderStation> orderStations = orderStationMapper.selectOrderStationList(orderStation);
            orderStations.forEach(x->{
                OrderStationItem orderStationItem = new OrderStationItem();
                orderStationItem.setOrderStationId(x.getId());
                List<OrderStationItem> orderStationItems = orderStationItemMapper.selectOrderStationItemList(orderStationItem);
                orderStationItems.forEach(y->{
                    //巡检项图片
                    StationItemFile stationItemFile = new StationItemFile();
                    stationItemFile.setStationItemId(y.getId());
                    List<StationItemFile> stationItemFiles = stationItemFileMapper.selectStationItemFileList(stationItemFile);
                    y.setStationItemFileList(stationItemFiles);
                });
                x.setStationItemList(orderStationItems);
            });
            workOrder.setOrderStationList(orderStations);
        }
        return workOrder;
    }

    @Override
    public WorkOrder selectWorkOrderDetailById(Long id)
    {
        WorkOrder workOrder = workOrderMapper.selectWorkOrderById(id);
        String[] split = workOrder.getExecutorIds().split(",");
        long[] longs = Arrays.stream(split).mapToLong(Long::valueOf).toArray();
        workOrder.setExecutorIdArr(longs);
        //工单执行人名称
        String excecutorNames = sysUserMapper.selectExecutorNamesByIds(longs);
        workOrder.setExecutorName(excecutorNames);
        //获取巡检站点以及巡检项
        OrderStation orderStation = new OrderStation();
        orderStation.setOrderId(id);
        List<OrderStation> orderStations = orderStationMapper.selectOrderStationList(orderStation);
//            orderStations.forEach(x->{
//                OrderStationItem orderStationItem = new OrderStationItem();
//                orderStationItem.setOrderStationId(x.getId());
//                List<OrderStationItem> orderStationItems = orderStationItemMapper.selectOrderStationItemList(orderStationItem);
//                orderStationItems.forEach(y->{
//                    //巡检项图片
//                    StationItemFile stationItemFile = new StationItemFile();
//                    stationItemFile.setStationItemId(y.getId());
//                    List<StationItemFile> stationItemFiles = stationItemFileMapper.selectStationItemFileList(stationItemFile);
//                    y.setStationItemFileList(stationItemFiles);
//                });
//                x.setStationItemList(orderStationItems);
//            });
        workOrder.setOrderStationList(orderStations);
        int count = (int)orderStations.stream().filter(x -> x.getStatus()  == 1).count();
        //判断是否可以点击完成
        if(OrderStatus.ORDER_COMPLETED.getKey()==workOrder.getOrderStatus().intValue()){
            if (orderStations.size() > 0 && orderStations.size() == count) {
                workOrder.setRemainHandle(1);
            } else {
                workOrder.setRemainHandle(0);
            }
        }else {
            workOrder.setRemainHandle(0);
        }
        if(OrderStatus.ORDER_REJECT.getKey()==workOrder.getOrderStatus().intValue()){
            //审核意见
            WorkOrderAudit workOrderAudit = new WorkOrderAudit();
            workOrderAudit.setOrderId(workOrder.getId());
            List<WorkOrderAudit> workOrderAudits = workOrderAuditMapper.selectWorkOrderAuditList(workOrderAudit);
            workOrder.setWorkOrderAudit(workOrderAudits.get((0)));
        }
        return workOrder;
    }

    /**
     * 查询工单列表
     *
     * @param workOrder 工单
     * @return 工单
     */
    @Override
    public List<WorkOrder> selectWorkOrderList(WorkOrder workOrder)
    {
        return workOrderMapper.selectWorkOrderList(workOrder);
    }

    /**
     * 新增工单
     *
     * @param workOrder 工单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWorkOrder(WorkOrder workOrder)
    {
        if(workOrder.getStationIds()==null||workOrder.getStationIds().length==0){
            throw new BaseException("请选择站点");
        }
        if(workOrder.getExecutorIds()==null){
            throw new BaseException("请选择执行人员");
        }
        if(workOrder.getGmtRequireStart()==null){
            throw new BaseException("请选择开始时间");
        }
        //生成工单号
        String prefix ="";
        if(OrderType.INSPECT_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))){
            prefix ="XJDD";
        }else if(OrderType.MAINTAIN_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))) {
            prefix ="BYDD";
        }else if(OrderType.UPHOLD_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))) {
            prefix ="WHDD";
        }else if(OrderType.REPAIR_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))) {
            prefix ="WXDD";
        }
        try {
            workOrder.setOrderSn(prefix+SeqGenTool.seq());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            workOrder.setCreator(loginUser.getUser().getUserId());
            workOrder.setGmtCreate(new Date());
            int i = workOrderMapper.insertWorkOrder(workOrder);
            if(i>0){
                List<OrderStation> orderStations = new ArrayList<>();
                Arrays.stream(workOrder.getStationIds()).forEach(x->{
                    OrderStation orderStation = new OrderStation();
                    orderStation.setStationId(x);
                    orderStation.setOrderId(workOrder.getId());
                    orderStations.add(orderStation);
                });
                orderStationMapper.batchInsert(orderStations);
            }
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("新增工单失败..");
        }
    }

    /**
     * 新增工单
     *
     * @param workOrder 工单
     * @return 结果
     */
    @Override
    @Transactional
    public int appSeedWorkOrder(WorkOrder workOrder)
    {
        if(workOrder.getStationCodes()==null||workOrder.getStationCodes().length==0){
            throw new BaseException("请选择站点");
        }
        if(workOrder.getExecutorIds()==null){
            throw new BaseException("请选择执行人员");
        }
        if(workOrder.getGmtRequireStart()==null){
            throw new BaseException("请选择开始时间");
        }
        //生成工单号
        String prefix ="";
        if(OrderType.INSPECT_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))){
            prefix ="XJDD";
        }else if(OrderType.MAINTAIN_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))) {
            prefix ="BYDD";
        }else if(OrderType.UPHOLD_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))) {
            prefix ="WHDD";
        }else if(OrderType.REPAIR_ORDER.equals(OrderType.getOrderType(workOrder.getOrderType()))) {
            prefix ="WXDD";
        }
        try {
            workOrder.setOrderSn(prefix+SeqGenTool.seq());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            workOrder.setCreator(loginUser.getUser().getUserId());
            workOrder.setGmtCreate(new Date());
            workOrder.setIsSeed(1);
            workOrder.setSeedUser(SecurityUtils.getLoginUser().getUser().getUserId());
            int i = workOrderMapper.insertWorkOrder(workOrder);
            if(i>0){
                List<OrderStation> orderStations = new ArrayList<>();
                Arrays.stream(workOrder.getStationCodes()).forEach(x->{
                    OrderStation orderStation = new OrderStation();
                    VStation vStation = vStationMapper.selectVStationByStationCode(x);
                    orderStation.setStationId(vStation.getId());
                    orderStation.setOrderId(workOrder.getId());
                    orderStations.add(orderStation);
                });
                orderStationMapper.batchInsert(orderStations);
            }
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("新增工单失败..");
        }
    }

    /**
     * 修改工单
     *
     * @param workOrder 工单
     * @return 结果
     */
    @Override
    @Transactional
    public int updateWorkOrder(WorkOrder workOrder)
    {
        if(workOrder.getExecutorIds()==null){
            throw new BaseException("请选择执行人员");
        }
        if(workOrder.getGmtRequireStart()==null){
            throw new BaseException("请选择开始时间");
        }
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            workOrder.setModifier(loginUser.getUser().getUserId());
            workOrder.setGmtModify(new Date());
            if(workOrder.getStationIds()!=null&&workOrder.getStationIds().length>0){
                orderStationMapper.deleteOrderStationByOrderId(workOrder.getId());
                List<OrderStation> orderStations = new ArrayList<>();
                Arrays.stream(workOrder.getStationIds()).forEach(x->{
                    OrderStation orderStation = new OrderStation();
                    orderStation.setStationId(x);
                    orderStation.setOrderId(workOrder.getId());
                    orderStations.add(orderStation);
                });
                orderStationMapper.batchInsert(orderStations);
            }
            return workOrderMapper.updateWorkOrder(workOrder);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("工单修改失败");
        }
    }

    /**
     * 批量删除工单
     *
     * @param ids 需要删除的工单ID
     * @return 结果
     */
    @Override
    public int deleteWorkOrderByIds(Long[] ids)
    {
        return workOrderMapper.deleteWorkOrderByIds(ids);
    }

    /**
     * 删除工单信息
     *
     * @param id 工单ID
     * @return 结果
     */
    @Override
    public int deleteWorkOrderById(Long id)
    {
        return workOrderMapper.deleteWorkOrderById(id);
    }

    @Override
    public WorkOrder selectLastOnWorkOrderByTaskId(Long planId) {
        return workOrderMapper.selectLastOnWorkOrderByTaskId(planId);
    }

    @Override
    public List<WorkOrderVO> listExecutorAppWorkOrder(WorkOrderQuery workOrderQuery) {
        Optional.ofNullable(workOrderQuery.getOrderStatus()).orElse(OrderStatus.ORDER_WAIT_START.getKey().intValue());
        WorkOrder workOrder = new WorkOrder();
        BeanUtils.copyProperties(workOrderQuery,workOrder);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        workOrder.setExecutorId(user.getUserId());
//        workOrder.setExecutorId(2L);
        return workOrderMapper.listWorkOrderBySelective(workOrder);
    }

    @Override
    public List<SysUser> getExecutorList() {
        SysUser sysUser = new SysUser();
//        sysUser.setDeptId(107L);
        return sysUserMapper.selectUserList(sysUser);
    }

    @Override
    public int updateWorkOrderByID(WorkOrder workOrder) {
        return workOrderMapper.updateWorkOrderByID(workOrder);
    }

    @Override
    public List<VStation> getWorkOrderStationList(Long id) {
        return workOrderMapper.getWorkOrderStationList(id);
    }

    @Override
    public int updateWorkOrderStatus(WorkOrder workOrder) {
        return workOrderMapper.updateWorkOrder(workOrder);
    }

    @Override
    public List<HashMap<String, Object>> workOrderMap() {
        List<HashMap<String, Object>> list = new ArrayList<>();
//        alarm: 1
//        alarmtimes: 12
//        aname: "陬市污水处理厂（常德首创）"
//        healthValue: 5
//        id: 43
//        leader: "向伟"
//        leaderphone: "15197668343"
//        offline: 1
//        startPoint: "111.3320,29.359"
//        status: 2
//        type: 1
        HashMap<String, Object> data1 = new HashMap<>();
        HashMap<String, Object> data2 = new HashMap<>();
        HashMap<String, Object> data3 = new HashMap<>();
        HashMap<String, Object> data4 = new HashMap<>();
        HashMap<String, Object> data5 = new HashMap<>();
        HashMap<String, Object> data6 = new HashMap<>();
        data1.put("id",42);
        data1.put("alarm",1);
        data1.put("aname","n");
        data1.put("leader","向前");
        data1.put("leaderphone","17715816063");
        data1.put("offline",1);
        data1.put("startPoint","111.3320,29.359");
        data1.put("status",2);
        data1.put("type",1);
        list.add(data1);

        data2.put("id",43);
        data2.put("alarm",1);
        data2.put("aname","taoyuan");
        data2.put("leader","欧阳");
        data2.put("leaderphone","16602746729");
        data2.put("offline",1);
        data2.put("startPoint","111.4864237,28.9282657");
        data2.put("status",3);
        data2.put("type",1);
        list.add(data2);

        data3.put("id",61);
        data3.put("aname","xuhui");
        data3.put("destination","China");
        data3.put("leaderphone","16602746729");
        data3.put("offline",1);
        data3.put("startPoint","114.42468098958334,30.503664008246528");
        data3.put("status",2);
        data3.put("type",2);
        data3.put("workStatus",1);
        list.add(data3);

        data4.put("id",62);
        data4.put("aname","zhangkaixiang");
        data4.put("destination","China");
        data4.put("leaderphone","13476237882");
        data4.put("offline",1);
        data4.put("startPoint","112.92480902777778,28.109087185329862");
        data4.put("status",2);
        data4.put("type",2);
        data4.put("workStatus",0);
        list.add(data4);
        //车辆
        data5.put("id",1002);
        data5.put("aname","苏EQX563");
        data5.put("driver","zcy");
        data5.put("leaderphone","13476237882");
        data5.put("startPoint","111.4764237,28.9782657");
        data5.put("status",2);
        data5.put("type",3);
        data5.put("peijian","配件");
        list.add(data5);

        data6.put("id",1003);
        data6.put("aname","苏EUI7623");
        data6.put("driver","hnx");
        data6.put("leaderphone","13476237882");
        data6.put("startPoint","111.4364237,28.8782657");
        data6.put("status",2);
        data6.put("type",3);
        data6.put("peijian","配件");
        list.add(data6);

        return list;
    }
}
